package com.ltx.blog_ltx.until;

import io.jsonwebtoken.*;

import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class jwtUntil {

    private static long time =1000*60*60*24*7;
    private static String signature="username";

    public static String createJwt(String username){
        System.out.println(username+"------1231321----------------");
        JwtBuilder builder = Jwts.builder();
        String jwtToken= builder
                .setHeaderParam("typ","JWt")
                .setHeaderParam("alg","HS256")
                .claim("username",username)
                .setSubject("userifno")
                .setExpiration(new Date(System.currentTimeMillis()+time))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();
        return jwtToken;
    }

    public static boolean parse(String token)
    {
        JwtParser parser = Jwts.parser();
        try {
            Jws<Claims> claimsJws = parser.setSigningKey(signature).parseClaimsJws(token);
            Claims body = claimsJws.getBody();
            System.out.println(body.get("username"));
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /***
     * 通过前端传过来的token可以解析到username，因为username是唯一的，所有我们可以通过username来找到是那个用户。
     * @param token
     * @return
     */
    public static String getTokenName(String token)
    {
        JwtParser parser = Jwts.parser();
            Jws<Claims> claimsJws = parser.setSigningKey(signature).parseClaimsJws(token);
            Claims body = claimsJws.getBody();
        System.out.println(body.get("username")+"=================================");
        return (String)body.get("username");
    }
}
